const fs = require('fs')
const https = require('https')
const http = require('http')
const path = require('path')
const xpath = require('xpath')
const dom = require('xmldom').DOMParser
const defaultConfig = require('./config')
// 图片宽度
const imgW = defaultConfig.imgWidth
// 每日任务upid
const upId = defaultConfig.upIdObj.mrrw
const {
	createCanvas,
	loadImage
} = require('canvas')
// 压缩
const imagemin = require('imagemin');
const imageminJpegtran = require('imagemin-jpegtran');
const imageminPngquant = require('imagemin-pngquant');

// 清空空数组
let trimSpace = (array) => {
	for (var i = 0; i < array.length; i++) {
		if (array[i] == "" || array[i] == " " || array[i] == null || typeof (array[i]) == "undefined") {
			array.splice(i, 1);
			i = i - 1;
		}
	}
	return array;
}

// 获取复刻先祖图片
let getAncestor = (upObj) => {
	return new Promise(async resFn => {
		let datas = await getUpimgList(upObj)
		let imgLists = []
		let titleList = []
		var doc = new dom().parseFromString(datas)
		xpath.select("//figure/figcaption/text()", doc).forEach(item => {
			titleList.push(item.data)
		})
		xpath.select("//figure/img/@data-src", doc).forEach((item) => {
			if (item.value.indexOf('.jpg') != -1) {
				imgLists.push('https:' + item.value)
			}
		})
		resFn({ fukeTime: titleList[0], fukeImg: imgLists[0] })
	})
}

// 获取up专栏资源 
let getUpimgList = (upObj) => {
	return new Promise(async resFn => {
		let json = await newHttp(https, 'get', `https://api.bilibili.com/x/space/article?mid=${upObj.id}`)
		let id = JSON.parse(json).data.articles[0].id
		let datas = await newHttp(https, 'get', `https://www.bilibili.com/read/cv${id}`)
		resFn(datas)
	})
}

// 处理每日任务图片
let getImgList = async (upObj) => {
	let datas = await getUpimgList(upObj)
	let titleList = []
	let imgLists = []
	var doc = new dom().parseFromString(datas)
	xpath.select("//figure/figcaption/text()", doc).forEach(item => {
		titleList.push(item.data)
	})
	xpath.select("//figure/img/@data-src", doc).forEach((item) => {
		if (item.value.indexOf('.jpg') != -1) {
			imgLists.push('https:' + item.value)
		}
	})
	let obj = []
	xpath.select("//figure/img", doc).forEach((item, is) => {
		let t = item.attributes
		obj.push({})
		for (let k in t) {
			if (t[k].name == 'height') {
				obj[is]["height"] = t[k].value
			}
			if (t[k].name == 'width') {
				obj[is]["width"] = t[k].value
			}
		}
		if (!obj[is].height) delete obj[is]

	})
	let sizeObj = {
		maxHeight: 0,
		itemLength: []
	}
	return new Promise(resFn => {
		trimSpace(obj).forEach((item, index) => {
			let w = imgW / item.width
			let h = Math.floor(w * item.height)
			sizeObj.maxHeight += h
			sizeObj.itemLength.push({ top: index == 0 ? 0 : sizeObj.itemLength[index - 1].height + sizeObj.itemLength[index - 1].top, height: h })
		})
		getImglistItem(imgLists, titleList, sizeObj, upObj).then(() => {
			console.log(upObj.name, "图片绘制完成")
			resFn()
		})
	})

}

// 绘制每日任务图片
let getImglistItem = (imgList, textList, sizeObj, upObj) => {
	return new Promise(async (resFn) => {
		const canvas = createCanvas(imgW, sizeObj.maxHeight + 100)
		const ctx = canvas.getContext('2d')
		for (let i = 0; i < imgList.length; i++) {
			let text = textList[i] == undefined ? '  ' : textList[i]
			let imgs = await loadImage(imgList[i])
			ctx.drawImage(imgs, 0, sizeObj.itemLength[i].top, imgW, sizeObj.itemLength[i].height);
			ctx.font = '20px Arial Unicode'
			ctx.fillStyle = '#ffba79'
			ctx.fillText(text, 20, sizeObj.itemLength[i].top + 50)
		}
		// 添加up名字头像
		ctx.fillStyle = '#f9749a'
		ctx.fillRect(0, sizeObj.maxHeight, imgW, 100)
		ctx.save();
		ctx.fillStyle = '#f9749a'
		ctx.arc(70, sizeObj.maxHeight + 50, 30, 0, 2 * Math.PI, false);
		// 从画布上裁剪出这个圆形
		ctx.clip();
		let iconP = await loadImage(upObj.img)
		ctx.drawImage(iconP, 40, sizeObj.maxHeight + 20, 60, 60);
		ctx.restore();
		ctx.fillStyle = '#fff'
		ctx.font = '30px Arial Unicode'
		ctx.fillText('b站:' + upObj.name, 120, sizeObj.maxHeight + 58)
		ctx.stroke()
		let imgName = `../../public/images/${upObj.imgName}.jpg`
		var out = fs.createWriteStream(path.join(__dirname, imgName)),
			stream = canvas.createPNGStream();
		stream.on('data', function (chunk) {
			out.write(chunk);
		});
		setTimeout(() => {
			(async () => {
				await imagemin([path.join(__dirname, imgName)], {
					destination: path.join(__dirname, '../../public/images'),
					plugins: [
						imageminJpegtran(),
						imageminPngquant({
							quality: [0.3, 0.5],
							dithering: 0.5
						})
					]
				});
				resFn()
			})();
		}, 5000)
	})
}

// 绘制疫情地区
function CanvasYiqin(arr, yiqinData, mryiqinData) {
	let arrLen = (arr.length + 1) * 40 + 500
	let yiqinDataLen = (yiqinData.length + 1) * 40
	const canvas = createCanvas(imgW + 100, arrLen + yiqinDataLen)
	const ctx = canvas.getContext('2d')
	// 每日疫情
	ctx.fillStyle = '#ffffff'
	ctx.fillRect(0, 0, imgW + 100, 400)
	ctx.save();
	ctx.fillStyle = '#000'
	ctx.font = '40px Arial Unicode'
	ctx.fillText('疫情简讯', 230, 55)
	ctx.font = '30px Arial Unicode'
	ctx.fillText('现有确诊', 20, 100)
	ctx.fillText('累计确诊', 310, 100)
	ctx.fillText('累计治愈', 20, 260)
	ctx.fillText('累计死亡', 310, 260)
	ctx.font = '56px Arial Unicode'
	ctx.fillStyle = '#e44a3d'
	ctx.fillText(mryiqinData.total.confirm - mryiqinData.total.dead - mryiqinData.total.heal, 20, 160)
	ctx.fillStyle = '#a31d13'
	ctx.fillText(mryiqinData.total.confirm, 310, 160)
	ctx.fillStyle = '#34aa70'
	ctx.fillText(mryiqinData.total.heal, 20, 320)
	ctx.fillStyle = '#000'
	ctx.fillText(mryiqinData.total.dead, 310, 320)
	ctx.font = '26px Arial Unicode'
	ctx.fillStyle = '#e44a3d'
	ctx.fillText('较昨日 ' + (mryiqinData.today.storeConfirm > 0 ? '+' + mryiqinData.today.storeConfirm : mryiqinData.today.storeConfirm), 20, 200)
	ctx.fillStyle = '#a31d13'
	ctx.fillText('较昨日 ' + (mryiqinData.today.confirm > 0 ? '+' + mryiqinData.today.confirm : mryiqinData.today.confirm), 310, 200)
	ctx.fillStyle = '#34aa70'
	ctx.fillText('较昨日 ' + (mryiqinData.today.heal > 0 ? '+' + mryiqinData.today.heal : mryiqinData.today.heal), 20, 360)
	ctx.fillStyle = '#000'
	ctx.fillText('较昨日 ' + (mryiqinData.today.dead > 0 ? '+' + mryiqinData.today.dead : mryiqinData.today.dead), 310, 360)
	ctx.save();
	// // 风险区域
	ctx.fillStyle = '#fff'
	ctx.fillRect(0, 400, imgW + 100, arrLen + yiqinDataLen - 400)
	ctx.font = '40px Arial Unicode'
	ctx.fillStyle = '#0000ff'
	ctx.fillText('风险区域总数:', 20, 470)
	if (arr.length > 22) {
		ctx.fillStyle = '#ff0000'
	} else if (arr.length > 12) {
		ctx.fillStyle = '#0000ff'
	} else {
		ctx.fillStyle = '#00ff00'
	}
	ctx.fillText(arr.length - 2, 280, 470)
	ctx.save();
	ctx.font = '16px Arial Unicode'
	ctx.fillStyle = '#000'
	for (let i = 0; i < arr.length; i++) {
		ctx.fillText(arr[i], 20, (i + 1) * 40 + 500)
	}
	ctx.save();

	// // 风险城市
	ctx.font = '20px Arial Unicode'
	ctx.fillStyle = '#ff0000'
	ctx.fillText('省市区', 20, arrLen)
	ctx.fillText('城市(区)', 180, arrLen)
	ctx.fillText('新增', 340, arrLen)
	ctx.fillText('现有', 440, arrLen)
	ctx.save();
	ctx.font = '16px Arial Unicode'
	ctx.fillStyle = '#000'
	for (let i = 0; i < yiqinData.length; i++) {
		ctx.fillText(yiqinData[i].province, 20, arrLen + (i + 1) * 40)
		ctx.fillText(yiqinData[i].city, 180, arrLen + (i + 1) * 40)
		ctx.fillText(yiqinData[i].confirmAdd, 340, arrLen + (i + 1) * 40)
		ctx.fillText(yiqinData[i].nowConfirm, 440, arrLen + (i + 1) * 40)
	}
	ctx.stroke()
	let imgName = `../../public/images/yiqin.png`
	var out = fs.createWriteStream(path.join(__dirname, imgName)),
		stream = canvas.createPNGStream();
	stream.on('data', function (chunk) {
		out.write(chunk);
	});
	setTimeout(() => {
		(async () => {
			await imagemin([path.join(__dirname, imgName)], {
				destination: path.join(__dirname, '../../public/images'),
				plugins: [
					imageminJpegtran(),
					imageminPngquant({
						quality: [0.3, 0.5],
						dithering: 0.5
					})
				]
			});
		})();
	}, 1000)
}
// 获取疫情
async function getYiQin() {
	let datas = await newHttp(http, 'get', 'http://www.gd.gov.cn/gdywdt/zwzt/yqfk/content/post_3021711.html')
	var doc = new dom().parseFromString(datas)
	var title = xpath.select("string(//div[@class='zw'])", doc)
	let arr = trimSpace(title.split(/\s/))
	arr.pop()
	let cityData = await newHttp(https, 'get', `https://api.inews.qq.com/newsqa/v1/query/inner/publish/modules/list?modules=statisGradeCityDetail`)
	let quyuData = JSON.parse(cityData).data.statisGradeCityDetail
	let tempData = await newHttp(https, 'get', `https://c.m.163.com/ug/api/wuhan/app/data/list-total`)
	let yiqinData = JSON.parse(tempData).data.chinaTotal
	CanvasYiqin(trimSpace(arr), quyuData, yiqinData)
}

// 获取up头像
let getUpImg = (upId) => {
	return new Promise(async resFn => {
		for (let key in upId) {
			let httpData = await newHttp(http, 'get', `http://api.bilibili.com/x/space/acc/info?mid=${upId[key].id}`)
			if (JSON.parse(httpData).data) {
				upId[key].img = JSON.parse(httpData).data.face
				upId[key].name = JSON.parse(httpData).data.name
			}

		}
		resFn(upId)
	})
}

// 把http变成promise
let newHttp = (c, m, u) => {
	return new Promise(resFn => {
		c[m](u, function (okdata) {
			let datas = ""
			okdata.setEncoding("utf8")
			okdata.on("data", chunk => datas += chunk)
			okdata.on("end", () => {
				resFn(datas)
			})

		})
	})
}

// 获取每日任务
let getListImg = () => {
	return new Promise(async resfn => {
		// 获取疫情
		getYiQin()
		// 获取up头像
		let upInfo = await getUpImg(upId)

		for (let i in upInfo) {
			await getImgList({
				id: upInfo[i].id,
				imgName: i + 'list',
				name: upInfo[i].name,
				img: upInfo[i].img
			})
		}



		resfn()
	})
}
// 随机取一句话
let getRandomInt = (number) => {
	return Math.floor(Math.random() * number)
}

module.exports = {
	getAncestor,
	getListImg,
	getRandomInt,
	getYiQin

}